package cn.xuchunh.campusbbs.ui.fragments;

import android.animation.ObjectAnimator;
import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.Animatable;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.view.animation.AccelerateDecelerateInterpolator;

import com.facebook.drawee.backends.pipeline.Fresco;
import com.facebook.drawee.controller.BaseControllerListener;
import com.facebook.drawee.controller.ControllerListener;
import com.facebook.drawee.drawable.ProgressBarDrawable;
import com.facebook.drawee.drawable.ScalingUtils;
import com.facebook.drawee.generic.GenericDraweeHierarchy;
import com.facebook.drawee.generic.GenericDraweeHierarchyBuilder;
import com.facebook.drawee.interfaces.DraweeController;
import com.facebook.drawee.view.SimpleDraweeView;
import com.facebook.imagepipeline.image.CloseableAnimatedBitmap;
import com.facebook.imagepipeline.image.CloseableStaticBitmap;
import com.facebook.imagepipeline.image.QualityInfo;
import com.facebook.imagepipeline.request.BasePostprocessor;
import com.facebook.imagepipeline.request.ImageRequest;
import com.facebook.imagepipeline.request.ImageRequestBuilder;
import com.facebook.rebound.Spring;
import com.facebook.rebound.SpringListener;
import com.facebook.rebound.SpringSystem;
import com.tumblr.backboard.Actor;
import com.tumblr.backboard.MotionProperty;
import com.tumblr.backboard.imitator.MotionImitator;
import com.tumblr.backboard.performer.Performer;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

import cn.xuchunh.campusbbs.R;
import cn.xuchunh.campusbbs.base.BaseActivity;
import cn.xuchunh.campusbbs.base.BaseFragment;
import cn.xuchunh.campusbbs.net.HttpRequestManager;
import cn.xuchunh.campusbbs.utils.AppUtil;
import cn.xuchunh.campusbbs.utils.IntentParamsKey;

/**
 *
 * Created by XuChunH on 2015/10/25.
 */
public class ImageFragment extends BaseFragment {

    public static final int COMPRESS_FORMAT_STATIC = 0;
    public static final int COMPRESS_FORMAT_ANIMATED = 1;

    private Uri uri;
    private int baseSystemUIVisibility = View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
            | View.SYSTEM_UI_FLAG_LAYOUT_STABLE;
    private int fullScreenFlag = View.SYSTEM_UI_FLAG_FULLSCREEN
            | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION;
    private boolean released = false;
    private int compressFormat = COMPRESS_FORMAT_STATIC;
    private Bitmap target;

    public static ImageFragment newInstance(Uri uri) {

        Bundle args = new Bundle();
        args.putParcelable(IntentParamsKey.URI, uri);
        ImageFragment fragment = new ImageFragment();
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    protected void initView(View view) {
        getActivity().getWindow().getDecorView().setSystemUiVisibility(baseSystemUIVisibility);
        SimpleDraweeView simpleDraweeView = ((SimpleDraweeView) view.findViewById(R.id.simple_drawee));

        DraweeController draweeController = Fresco.newDraweeControllerBuilder()
                .setUri(uri)
                .setControllerListener(controllerListener)
                .setOldController(simpleDraweeView.getController())
                .build();
        GenericDraweeHierarchy hierarchy = new GenericDraweeHierarchyBuilder(getResources())
                .setProgressBarImage(new ProgressBarDrawable())
                .setActualImageScaleType(ScalingUtils.ScaleType.FIT_CENTER)
                .setFailureImage(getResources().getDrawable(R.drawable.ic_broken_image_white_48dp), ScalingUtils.ScaleType.CENTER)
                .build();
        simpleDraweeView.setController(draweeController);
        simpleDraweeView.setHierarchy(hierarchy);
    }

    @Override
    protected void beforeInitView() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            fullScreenFlag |= View.SYSTEM_UI_FLAG_IMMERSIVE;
        }
        setContentViewRes(R.layout.fragment_image);
        setHasOptionsMenu(true);
    }

    @Override
    public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
        inflater.inflate(R.menu.menu_image, menu);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        if (item.getItemId() == R.id.menu_image_save) {
            new SavePictureTast().execute();
            return true;
        } else {
            return super.onOptionsItemSelected(item);

        }
    }

    @Override
    protected void handleArgs(Bundle args) {
        if (args != null) {
            uri = args.getParcelable(IntentParamsKey.URI);
        }
    }

    private void changeSystemUIVisibility() {
        View decorView = getActivity().getWindow().getDecorView();
        ObjectAnimator objectAnimator;
        if ((decorView.getSystemUiVisibility() ^ baseSystemUIVisibility) == 0) {
            decorView.setSystemUiVisibility(fullScreenFlag);
            objectAnimator = ObjectAnimator.ofFloat(((BaseActivity) getActivity()).getToolbar(), "alpha", 1, 0)
                    .setDuration(500);

        } else {
            decorView.setSystemUiVisibility(baseSystemUIVisibility);
            objectAnimator = ObjectAnimator.ofFloat(((BaseActivity) getActivity()).getToolbar(), "alpha", 0, 1)
                    .setDuration(500);

        }
        objectAnimator.setInterpolator(new AccelerateDecelerateInterpolator());
        objectAnimator.start();
    }

    ControllerListener controllerListener = new BaseControllerListener() {
        @Override
        public void onFailure(String id, Throwable throwable) {
            super.onFailure(id, throwable);
        }

        @Override
        public void onFinalImageSet(String id, Object imageInfo, Animatable animatable) {
            super.onFinalImageSet(id, imageInfo, animatable);
            if (imageInfo instanceof CloseableStaticBitmap) {
                CloseableStaticBitmap closeableStaticBitmap = (CloseableStaticBitmap) imageInfo;
                target = closeableStaticBitmap.getUnderlyingBitmap();
            } else if (imageInfo instanceof CloseableAnimatedBitmap) {
                target = ((CloseableAnimatedBitmap) imageInfo).getUnderlyingBitmap();
                compressFormat = COMPRESS_FORMAT_ANIMATED;
            }

        }

        @Override
        public void onIntermediateImageFailed(String id, Throwable throwable) {
            super.onIntermediateImageFailed(id, throwable);
        }

        @Override
        public void onIntermediateImageSet(String id, Object imageInfo) {
            super.onIntermediateImageSet(id, imageInfo);
        }

        @Override
        public void onRelease(String id) {
            released = true;
            super.onRelease(id);
        }

        @Override
        public void onSubmit(String id, Object callerContext) {
            super.onSubmit(id, callerContext);
        }
    };

    private class SavePictureTast extends AsyncTask<Bitmap, Void, Boolean> {

        @Override
        protected void onPostExecute(Boolean aBoolean) {
            if (aBoolean) {
                showToast("保存图片成功");
            } else {
                showToast("保存图片失败");
            }
        }

        @Override
        protected Boolean doInBackground(Bitmap... params) {

            if (target == null || released || target.isRecycled()) {
                return false;
            }

            if (compressFormat == COMPRESS_FORMAT_STATIC) {
                return saveStaticPicture();
            } else {
                return saveAnimatedPicture();
            }
        }

        private boolean saveStaticPicture() {
            String filePath = AppUtil.getPicturesPath(getActivity()) + System.currentTimeMillis() + ".jpg";
            File file = new File(filePath);
            if (file.exists()) {
                file.delete();
            }
            try {
                file.createNewFile();
            } catch (IOException e) {
                return false;
            }
            FileOutputStream outputStream = null;
            boolean result = true;
            try {
                outputStream = new FileOutputStream(file);
                target.compress(Bitmap.CompressFormat.JPEG, 100, outputStream);

            } catch (FileNotFoundException e) {
                result = false;
            } finally {
                if (outputStream != null) {
                    try {
                        outputStream.flush();
                        outputStream.close();
                    } catch (IOException ignored) {
                    }
                }
            }
            return result;
        }

        private boolean saveAnimatedPicture() {
            return HttpRequestManager.getInstance(getActivity()).savePicture(uri.toString());
        }
    }

}
